﻿if exists (select * from sysobjects where name like N'%sp_DMQuyenHoaDon_InsertUpdate%')
	drop proc sp_DMQuyenHoaDon_InsertUpdate
go
create proc sp_DMQuyenHoaDon_InsertUpdate
	@MaQuyenHoaDon varchar(50) = null,
	@TenQuyenHoaDon nvarchar(50) = null,
	@SoHoaDonTu int = null,
	@SoHoaDonDen int = null,
	@STT int = null,
	@IsUse bit = null,
	@CreateBy int = null,
	@ModifiedBy int = null,
	@ModifiedOn datetime = null,
	@XML ntext = null
as
begin
	declare @iDoc int
	exec sp_xml_preparedocument @iDoc output, @XML
	select @MaQuyenHoaDon = MaQuyenHoaDon, @TenQuyenHoaDon = TenQuyenHoaDon, 
		@SoHoaDonTu = SoHoaDonTu, @SoHoaDonDen = SoHoaDonDen, @STT = STT, @IsUse = IsUse, 
		@CreateBy = CreateBy, @ModifiedBy = ModifiedBy, @ModifiedOn = ModifiedOn
	from openxml (@iDoc, N'/Root/DMQuyenHoaDon')
	with (MaQuyenHoaDon varchar(50), TenQuyenHoaDon nvarchar(50), SoHoaDonTu int, SoHoaDonDen int, 
		STT int, IsUse bit, CreateBy int,
		ModifiedBy int, ModifiedOn datetime)
	exec sp_xml_removedocument @iDoc 

	if not exists (select * from DMQuyenHoaDon where MaQuyenHoaDon = @MaQuyenHoaDon)
	begin
		insert into DMQuyenHoaDon (MaQuyenHoaDon, TenQuyenHoaDon, SoHoaDonTu, SoHoaDonDen, STT, IsUse, CreateBy)
		values (@MaQuyenHoaDon, @TenQuyenHoaDon, @SoHoaDonTu, @SoHoaDonDen, @STT, 1, @CreateBy )

		update DMQuyenHoaDon 
		set IsUse = 0
		where MaQuyenHoaDon <> @MaQuyenHoaDon
	end

	else
	begin
		if @IsUse = 1
		begin	
			update DMQuyenHoaDon 
			set @IsUse = 1, 
				MaQuyenHoaDon = @MaQuyenHoaDon,
				TenQuyenHoaDon = @TenQuyenHoaDon,
				SoHoaDonTu = @SoHoaDonTu,
				SoHoaDonDen = @SoHoaDonDen,
				STT = @STT,
				ModifiedBy = @ModifiedBy,
				ModifiedOn = @ModifiedOn
			where MaQuyenHoaDon = @MaQuyenHoaDon 

			update DMQuyenHoaDon 
			set IsUse = 0
			where MaQuyenHoaDon <> @MaQuyenHoaDon
		end

		else
		begin
			update DMQuyenHoaDon 
			set @IsUse = 0, 
				MaQuyenHoaDon = @MaQuyenHoaDon,
				TenQuyenHoaDon = @TenQuyenHoaDon,
				SoHoaDonTu = @SoHoaDonTu,
				SoHoaDonDen = @SoHoaDonDen,
				STT = @STT,
				ModifiedBy = @ModifiedBy,
				ModifiedOn = @ModifiedOn
			where MaQuyenHoaDon = @MaQuyenHoaDon 
		end
	end
end